 package com.rt.shop.view.admin.sellers.action;
 
 import java.awt.Font;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.csvreader.CsvReader;
import com.rt.shop.common.annotation.SecurityMapping;
import com.rt.shop.common.tools.CommUtil;
import com.rt.shop.entity.Accessory;
import com.rt.shop.entity.Album;
import com.rt.shop.entity.Goods;
import com.rt.shop.entity.GoodsClass;
import com.rt.shop.entity.Store;
import com.rt.shop.entity.StoreGrade;
import com.rt.shop.entity.User;
import com.rt.shop.entity.UserGoodsClass;
import com.rt.shop.entity.Watermark;
import com.rt.shop.mv.JModelAndView;
import com.rt.shop.service.IAccessoryService;
import com.rt.shop.service.IAlbumService;
import com.rt.shop.service.IGoodsClassService;
import com.rt.shop.service.IGoodsService;
import com.rt.shop.service.IStoreGradeService;
import com.rt.shop.service.IStoreService;
import com.rt.shop.service.ISysConfigService;
import com.rt.shop.service.IUserConfigService;
import com.rt.shop.service.IUserGoodsClassService;
import com.rt.shop.service.IUserService;
import com.rt.shop.service.IWatermarkService;
import com.rt.shop.tools.StoreTools;
import com.rt.shop.util.SecurityUserHolder;
 
 @Controller
 public class TaobaoSellerAction
 {
 
   @Autowired
   private ISysConfigService configService;
   @Autowired
   private IStoreService storeService;
   
   @Autowired
   private IStoreGradeService storeGradeService;
 
   @Autowired
   private IUserConfigService userConfigService;
 
   @Autowired
   private IGoodsClassService goodsClassService;
 
   @Autowired
   private IUserGoodsClassService userGoodsClassService;
 
   @Autowired
   private IGoodsService goodsService;
 
   @Autowired
   private IUserService userService;
 
   @Autowired
   private IAlbumService albumService;
 
   @Autowired
   private IAccessoryService accessoryService;
 
   @Autowired
   private IWatermarkService waterMarkService;
 
   @Autowired
   private StoreTools storeTools;
 
   @SecurityMapping(display = false, rsequence = 0, title="导入淘宝CSV", value="/seller/taobao.htm*", rtype="seller", rname="淘宝导入", rcode="taobao_seller", rgroup="淘宝管理")
   @RequestMapping({"/seller/taobao.htm"})
   public ModelAndView taobao(HttpServletRequest request, HttpServletResponse response)
   {
     ModelAndView mv = new JModelAndView(
       "user/default/usercenter/taobao.html", 
       this.configService.getSysConfig(), 
       this.userConfigService.getUserConfig(), 0, request, response);
     String taobao_upload_status = CommUtil.null2String(request.getSession(
       false).getAttribute("taobao_upload_status"));
     if (taobao_upload_status.equals("")) {
      
      
       String sql="where user_id='"+SecurityUserHolder.getCurrentUser().getId()+"' and display=1 and parent.id is null order by sequence asc";
       List ugcs = this.userGoodsClassService.selectList(sql,null);
       //  .query("select obj from UserGoodsClass obj where obj.user.id=:user_id and obj.display=:display and obj.parent.id is null order by obj.sequence asc", 
      
      
       List gcs = this.goodsClassService.selectList("where display=1 and parent_id is null", "sequence asc");
       //  .query("select obj from GoodsClass obj where obj.parent.id is null and obj.display=:display order by obj.sequence asc", 
       mv.addObject("gcs", gcs);
       mv.addObject("ugcs", ugcs);
     }
     if (taobao_upload_status.equals("upload_img")) {
       mv = new JModelAndView(
         "user/default/usercenter/taobao_import_img.html", 
         this.configService.getSysConfig(), 
         this.userConfigService.getUserConfig(), 0, request, 
         response);
       HashMap params = new HashMap();
       params.put("user_id", SecurityUserHolder.getCurrentUser().getId());
       Album sAlbum=new Album();
       sAlbum.setUser_id(SecurityUserHolder.getCurrentUser().getId());
       List alubms = this.albumService.selectList(sAlbum);
       //  "select obj from Album obj where obj.user.id=:user_id", 
       mv.addObject("alubms", alubms);
       mv.addObject("already_import_count", request.getSession(false)
         .getAttribute("already_import_count"));
       mv.addObject("no_import_count", request.getSession(false)
         .getAttribute("no_import_count"));
       mv.addObject("jsessionid", request.getSession().getId());
     }
     if (taobao_upload_status.equals("upload_finish")) {
       mv = new JModelAndView(
         "user/default/usercenter/taobao_import_finish.html", 
         this.configService.getSysConfig(), 
         this.userConfigService.getUserConfig(), 0, request, 
         response);
     }
     return mv;
   }
   @SecurityMapping(display = false, rsequence = 0, title="导入淘宝CSV", value="/seller/taobao_import_csv.htm*", rtype="seller", rname="淘宝导入", rcode="taobao_seller", rgroup="淘宝管理")
   @RequestMapping({"/seller/taobao_import_csv.htm"})
   public ModelAndView taobao_import_csv(HttpServletRequest request, HttpServletResponse response, String gc_id3, String ugc_ids) {
     ModelAndView mv = new JModelAndView(
       "user/default/usercenter/taobao_import_img.html", 
       this.configService.getSysConfig(), 
       this.userConfigService.getUserConfig(), 0, request, response);
     String taobao_upload_status = CommUtil.null2String(request.getSession(
       false).getAttribute("taobao_upload_status"));
     String path = request.getSession().getServletContext().getRealPath("") + 
       File.separator + "csv";
     int already_import_count = 0;
     int no_import_count = 0;
     List taobao_goods_list = new ArrayList();
     try {
       Map map = CommUtil.saveFileToServer(request, "taobao_cvs", path, 
         "taobao.cvs", null);
       if (!map.get("fileName").equals("")) {
         String csvFilePath = path + File.separator + "taobao.cvs";
         CsvReader reader = new CsvReader(csvFilePath, '\t', 
           Charset.forName("UTF-16LE"));
         reader.readHeaders();
         int goods_name_pos = 0;
         int goods_price_pos = 7;
         int goods_count_pos = 9;
         int goods_status_pos = 20;
         int goods_transfee_pos = 11;
         int goods_recommend_pos = 21;
         int goods_detail_pos = 24;
         int goods_photo_pos = 35;
         User user = SecurityUserHolder.getCurrentUser();
         Album album = this.albumService.getDefaultAlbum(user.getId());
         if (album == null) {
           album = new Album();
           album.setAddTime(new Date());
           album.setAlbum_name("默认相册");
           album.setAlbum_sequence(-10000);
           album.setAlbum_default(true);
           this.albumService.insertSelective(album);
         }
         Store store=storeService.selectById(user.getStore_id());
         String img_path = this.storeTools.createUserFolderURL(
           this.configService.getSysConfig(), user.getStore_id());
         while (reader.readRecord()) {
           
           StoreGrade grade = storeGradeService.selectById(store.getGrade_id());
           Goods sGoods=new Goods();
           sGoods.setGoods_store_id(store.getId());
           List<Goods> storeGoods=goodsService.selectList(sGoods);
           if ((grade.getGoodsCount() == 0) || 
             (storeGoods.size() < grade
             .getGoodsCount())) {
             Goods goods = new Goods();
             goods.setGoods_name(reader.get(goods_name_pos));
             goods.setStore_price(BigDecimal.valueOf(
               CommUtil.null2Double(reader.get(goods_price_pos))));
             goods.setGoods_price(goods.getStore_price());
             goods.setGoods_inventory(CommUtil.null2Int(reader
               .get(goods_count_pos)));
             goods.setGoods_status(CommUtil.null2Int(reader
               .get(goods_status_pos)));
             goods.setGoods_recommend(CommUtil.null2Boolean(reader
               .get(goods_recommend_pos)));
             goods.setGoods_details(reader.get(goods_detail_pos));
             goods.setGoods_store(store);
             goods.setGoods_transfee(CommUtil.null2Int(reader
               .get(goods_transfee_pos)) - 1);
             goods.setGoods_current_price(goods.getStore_price());
             goods.setAddTime(new Date());
             goods.setGoods_seller_time(new Date());
             GoodsClass gc = this.goodsClassService
               .selectById(CommUtil.null2Long(gc_id3));
             goods.setGc(gc);
             String[] ugc_id_list = ugc_ids.split(",");
             for (String ugc_id : ugc_id_list) {
               UserGoodsClass ugc = this.userGoodsClassService
                 .selectById(CommUtil.null2Long(ugc_id));
               goods.getGoods_ugcs().add(ugc);
             }
             this.goodsService.insertSelective(goods);
             taobao_goods_list.add(goods);
             already_import_count++;
           } else {
             no_import_count++;
             mv = new JModelAndView("error.html", 
               this.configService.getSysConfig(), 
               this.userConfigService.getUserConfig(), 1, 
               request, response);
             mv.addObject("op_title", 
               "您的店铺等级只允许上传" + grade.getGoodsCount() + "件商品!");
             mv.addObject("url", CommUtil.getURL(request) + 
               "/seller/store_grade.htm");
             break;
           }
         }
         reader.close();
       }
     }
     catch (IOException e) {
       e.printStackTrace();
     }
     if (already_import_count > 0) {
       HashMap params = new HashMap();
       params.put("user_id", SecurityUserHolder.getCurrentUser().getId());
       Album sAlbum=new Album();
       sAlbum.setUser_id(SecurityUserHolder.getCurrentUser().getId());
       List alubms = this.albumService.selectList(sAlbum);
        // "select obj from Album obj where obj.user.id=:user_id", 
       mv.addObject("alubms", alubms);
       mv.addObject("jsessionid", request.getSession().getId());
       request.getSession(false).setAttribute("taobao_goods_list", 
         taobao_goods_list);
       request.getSession(false).setAttribute("taobao_upload_status", 
         "upload_img");
       request.getSession(false).setAttribute("already_import_count", 
         Integer.valueOf(already_import_count));
       request.getSession(false).setAttribute("no_import_count", 
         Integer.valueOf(no_import_count));
     }
     mv.addObject("already_import_count", Integer.valueOf(already_import_count));
     mv.addObject("no_import_count", Integer.valueOf(no_import_count));
     return mv;
   }
   @SecurityMapping(display = false, rsequence = 0, title="上传淘宝图片", value="/seller/taobao_img_upload.htm*", rtype="seller", rname="淘宝导入", rcode="taobao_seller", rgroup="淘宝管理")
   @RequestMapping({"/seller/taobao_img_upload.htm"})
   public void taobao_img_upload(HttpServletRequest request, HttpServletResponse response, String user_id, String album_id) {
     String csv_path = request.getSession().getServletContext()
       .getRealPath("") + 
       File.separator + "csv";
     try {
       String csvFilePath = csv_path + File.separator + "taobao.cvs";
       CsvReader reader = new CsvReader(csvFilePath, '\t', 
         Charset.forName("UTF-16LE"));
       reader.readHeaders();
       int goods_name_pos = 0;
       int goods_price_pos = 7;
       int goods_photo_pos = 35;
       User user = this.userService
         .selectById(CommUtil.null2Long(user_id));
       Store store=storeService.selectById(user.getStore_id());
         StoreGrade grade = storeGradeService.selectById(store.getGrade_id());
       String photo_path = this.storeTools.createUserFolder(request, 
         this.configService.getSysConfig(), user.getStore_id());
       String photo_url = this.storeTools.createUserFolderURL(
         this.configService.getSysConfig(), user.getStore_id());
       MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
       CommonsMultipartFile file = (CommonsMultipartFile)multipartRequest
         .getFile("imgFile");
       String upload_img_name = file.getOriginalFilename();
       upload_img_name = upload_img_name.substring(0, 
         upload_img_name.indexOf("."));
       double fileSize = Double.valueOf(file.getSize()).doubleValue();
       fileSize /= 1048576.0D;
       double csize = CommUtil.fileSize(new File(photo_path));
       double remainSpace = 0.0D;
       if (grade.getSpaceSize() != 0.0F)
         remainSpace = (grade.getSpaceSize() * 1024.0F - csize) * 1024.0D;
       else {
         remainSpace = 10000000.0D;
       }
       Map json_map = new HashMap();
       List<Goods> goods_list = (List)request.getSession(false)
         .getAttribute("taobao_goods_list");
       System.out.println(goods_list);
       System.out.println(SecurityUserHolder.getCurrentUser());
       Goods goods = new Goods();
       String[] photo_list = new String[0];
       while (reader.readRecord()) {
         if (reader.get(goods_photo_pos).indexOf(upload_img_name) >= 0) {
           String goods_name = reader.get(goods_name_pos);
           double goods_price = CommUtil.null2Double(reader
             .get(goods_price_pos));
           photo_list = reader.get(goods_photo_pos).split(";");
           for (Goods temp_goods : goods_list) {
             if ((!temp_goods.getGoods_name().equals(goods_name)) || 
               (CommUtil.null2Double(temp_goods
               .getGoods_price()) != goods_price)) continue;
             goods = temp_goods;
           }
         }
       }
 
       reader.close();
       if (goods != null)
       {
         if (remainSpace > fileSize) {
           try {
             Map map = CommUtil.saveFileToServer(request, "imgFile", 
               photo_path, upload_img_name + ".tbi", null);
            
             Watermark sWatermark=new Watermark();
             sWatermark.setStore_id(store.getId());
             List wms = this.waterMarkService.selectList(sWatermark);
             //  .query("select obj from WaterMark obj where obj.store.id=:store_id", 
             if (wms.size() > 0) {
               Watermark mark = (Watermark)wms.get(0);
               Accessory wm_image=accessoryService.selectById(mark.getWm_image_id());
               if (mark.getWm_image_open()) {
                 String pressImg = request.getSession()
                   .getServletContext().getRealPath("") + 
                   File.separator + 
                   wm_image.getPath() + 
                   File.separator + 
                   wm_image.getName();
                 String targetImg = photo_path + File.separator + 
                   map.get("fileName");
                 int pos = mark.getWm_image_pos();
                 float alpha = mark.getWm_image_alpha();
                 CommUtil.waterMarkWithImage(pressImg, 
                   targetImg, pos, alpha);
               }
               if (mark.getWm_text_open()) {
                 String targetImg = photo_path + File.separator + 
                   map.get("fileName");
                 int pos = mark.getWm_text_pos();
                 String text = mark.getWm_text();
                 String markContentColor = mark
                   .getWm_text_color();
                 CommUtil.waterMarkWithText(
                   targetImg, 
                   targetImg, 
                   text, 
                   markContentColor, 
                   new Font(mark.getWm_text_font(), 
                   1, mark
                   .getWm_text_font_size()), 
                   pos, 100.0F);
               }
             }
             Accessory image = new Accessory();
             image.setAddTime(new Date());
             image.setExt((String)map.get("mime"));
             image.setPath(photo_url);
             image.setWidth(CommUtil.null2Int(map.get("width")));
             image.setHeight(CommUtil.null2Int(map.get("height")));
             image.setName(CommUtil.null2String(map.get("fileName")));
             image.setUser(user);
             Album album = null;
             if ((album_id != null) && (!album_id.equals(""))) {
               album = this.albumService.selectById(
                 CommUtil.null2Long(album_id));
             } else {
               album = this.albumService.getDefaultAlbum(
                 CommUtil.null2Long(user_id));
               if (album == null) {
                 album = new Album();
                 album.setAddTime(new Date());
                 album.setAlbum_name("默认相册");
                 album.setAlbum_sequence(-10000);
                 album.setAlbum_default(true);
                 this.albumService.insertSelective(album);
               }
             }
             image.setAlbum(album);
             this.accessoryService.insertSelective(image);
             goods.getGoods_photos().add(image);
             this.goodsService.updateSelectiveById(goods);
             String imageServer = this.configService.getSysConfig().getImageWebServer();
             String isUrl = (imageServer == ""||imageServer == null) ? CommUtil.getURL(request):imageServer;
             json_map.put("url", isUrl + "/" + photo_url+ "/" + image.getName());
             json_map.put("id", image.getId());
             json_map.put("remainSpace", 
               Double.valueOf(remainSpace == 10000000.0D ? 0.0D : 
               remainSpace));
 
             String ext = image.getExt().indexOf(".") < 0 ? "." + 
               image.getExt() : image.getExt();
             String source = request.getSession()
               .getServletContext().getRealPath("/") + 
               image.getPath() + 
               File.separator + 
               image.getName();
             String target = source + "_small" + ext;
             CommUtil.createSmall(source, target, this.configService
               .getSysConfig().getSmallWidth(), 
               this.configService.getSysConfig()
               .getSmallHeight());
           }
           catch (IOException e) {
             e.printStackTrace();
           }
         } else {
           json_map.put("url", "");
           json_map.put("id", "");
           json_map.put("remainSpace", Integer.valueOf(0));
         }
       }
 
     }
     catch (IOException e)
     {
       e.printStackTrace();
     }
     request.getSession(false).setAttribute("taobao_upload_status", 
       "upload_finish");
   }
   @SecurityMapping(display = false, rsequence = 0, title="淘宝导入完成", value="/seller/taobao_import_finish.htm*", rtype="seller", rname="淘宝导入", rcode="taobao_seller", rgroup="淘宝管理")
   @RequestMapping({"/seller/taobao_import_finish.htm"})
   public ModelAndView taobao_import_finish(HttpServletRequest request, HttpServletResponse response) {
     ModelAndView mv = new JModelAndView(
       "user/default/usercenter/taobao_import_finish.html", 
       this.configService.getSysConfig(), 
       this.userConfigService.getUserConfig(), 0, request, response);
     request.getSession(false).removeAttribute("taobao_upload_status");
     request.getSession(false).removeAttribute("taobao_goods_list");
     request.getSession(false).removeAttribute("already_import_count");
     request.getSession(false).removeAttribute("no_import_count");
     return mv;
   }
 
   @RequestMapping({"/seller/taobao_authorize.htm"})
   public ModelAndView taobao_authorize(HttpServletRequest request, HttpServletResponse response, String code, String state)
   {
     ModelAndView mv = new JModelAndView(
       "user/default/usercenter/taobao_import_finish.html", 
       this.configService.getSysConfig(), 
       this.userConfigService.getUserConfig(), 0, request, response);
 
     return mv;
   }
 }


 
 
 